package com.hk.employeemanagementsystem.filter;

import com.hk.employeemanagementsystem.service.impl.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author by 何坤
 * @Classname UsernameAndPasswordFilter
 * @Description TODO
 * @Date 2020/1/1 20:20
 */
@Component
public class UsernameAndPasswordFilter extends OncePerRequestFilter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SecurityService securityService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if (("/login").equals(httpServletRequest.getRequestURI()) && ("POST").equals(httpServletRequest.getMethod())){
            String username = httpServletRequest.getParameter("phone");
            CharSequence password = httpServletRequest.getParameter("password");
            UserDetails userDetails = this.securityService.loadUserByUsername(username);
            String password1 = userDetails.getPassword();
            if (!passwordEncoder.matches(password, password1)){
                httpServletResponse.setContentType("Application/json;charset=utf-8");
                PrintWriter writer = httpServletResponse.getWriter();
                writer.write("{\"success\":false, \"message\":\"登录失败\"}");
                writer.flush();
                writer.close();
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
